<?php

namespace app\api\controller\kuyou\third;
use think\Db;
class Goods extends Thirds
{
    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';
    protected $web_site    = '';
    protected $goods_image = '/assets/addons/kuyou/img/noimage.png';

    public function _initialize()
    {
        parent::_initialize();
        $this->web_site = $this->request->server('HTTP_ORIGIN');
    }

    /**
     * 获取商品分类
     * @ApiMethod (POST)
     * @param int $pid 父级ID
     */
    public function goodsTypeList()
    {
        $data = input();
        $pid = isset($data['pid'])?$data['pid']:0;
        $where = [];
        if($pid){
            $where['pid'] = $pid;
        }else{
            $where['pid'] = 0;
        }
        $where['status'] = '1';
        $list = Db::name('kuyou_goods_type')->where($where)
            ->field('id,pid,supplier_type_name as name,supplier_type_image as image,FROM_UNIXTIME(updatetime,\'%Y-%m-%d\') as updatetime')
            ->select();

        foreach ($list as $list_k=>$list_v){
            if(empty($list_v['image'])){
                $list_v['image'] = $this->goods_image;
            }
            $list[$list_k]['image'] = $this->web_site.$list_v['image'];
        }
        $this->success('查询成功',$list,200);
    }

    /**
     * 获取商品列表
     * @ApiMethod (POST)
     */
    public function getGoodsList()
    {
        $data = input();
        $page = isset($data['page'])?$data['page']:1;
        $page = empty($page)?1:$page;
        $limit = isset($data['limit'])?$data['limit']:10;
        $limit = empty($limit)?10:$limit;

        $where = [];
        $keyword = isset($data['keyword'])?$data['keyword']:'';
        if(!empty($keyword)){
            $where['g.goods_code|g.goods_name|g.goods_barcode'] = ['like','%'.$keyword.'%'];
        }
        $goods_type_id = isset($data['goods_type_id'])?$data['goods_type_id']:'';
        if(!empty($goods_type_id)){
            $goods_type_ids = Db::name('kuyou_goods_type')->where(['path'=>['like','%,'.$goods_type_id.',%']])->column('id');
            $goods_type_ids[] = $goods_type_id;
            $where['g.goods_type_id'] = ['in',$goods_type_ids];
        }
        $where['g.status'] = '1';

        $tag = isset($data['tag'])?$data['tag']:'';
        if(!empty($tag)){
            $where['g.tag'] = ['like','%'.$tag.'%'];
        }

        $list = Db::name('kuyou_goods')->alias('g')
            ->join('kuyou_unit u','g.unit_id=u.id')
            ->where($where)
            ->page($page,$limit)
            ->field('g.id,g.goods_code,g.goods_type_id,g.goods_name,g.goods_barcode,g.note,g.goods_specification_id as goods_spec,g.unit_id,u.name as unit_name,g.more_unit
                ,g.purchase,g.market_sell_price,g.wholesale_price,g.vip_price,g.discount,g.discount2,g.goods_image,g.inventory as stock,FROM_UNIXTIME(g.updatetime,\'%Y-%m-%d %H:%i:%s\') as updatetime')
            ->order(['g.sale_number'=>'DESC','g.id'=>'DESC'])
            ->select();

        foreach ($list as $list_k=>$list_v){
            $unit_data = $this->getGoodsUnit($list_v['id'],$list_v['unit_id']);

            $list[$list_k]['purchase'] = isset($unit_data[0]['purchase'])?$unit_data[0]['purchase']:0;
            $list[$list_k]['market_sell_price'] = isset($unit_data[0]['market_sell_price'])?$unit_data[0]['market_sell_price']:0;
            $list[$list_k]['wholesale_price'] = isset($unit_data[0]['wholesale_price'])?$unit_data[0]['wholesale_price']:0;
            $list[$list_k]['vip_price'] = isset($unit_data[0]['vip_price'])?$unit_data[0]['vip_price']:0;
            $list[$list_k]['discount'] = isset($unit_data[0]['discount'])?$unit_data[0]['discount']:0;
            $list[$list_k]['discount2'] = isset($unit_data[0]['discount2'])?$unit_data[0]['discount2']:0;

            if(empty($list_v['goods_image'])){
                $list_v['goods_image'] = $this->goods_image;
            }
            $list[$list_k]['goods_image'] = $this->web_site.$list_v['goods_image'];

            $unit = Db::name('kuyou_unit')->where(['id'=>$list_v['unit_id']])->field('id,name')->find();
            if($unit){
                $unit_name = $unit['name'];
                $rowadvance_rate = '1';
                if($list_v['more_unit']==1){
                    $more_unit = Db::name('kuyou_unit_conversion')->alias('uc')
                        ->join('kuyou_unit u','u.id=uc.vice_unit')
                        ->where(['uc.main_unit'=>$unit['id']])
                        ->order('uc.advance_rate','ASC')
                        ->field('uc.vice_unit,u.name,u.id,uc.advance_rate')
                        ->select();
                    foreach ($more_unit as $unit_k=>$unit_v){
                        $unit_name .= ','.$unit_v['name'];
                        $rowadvance_rate .= ':'.$unit_v['advance_rate'];
                    }
                    $list[$list_k]['unit_name'] = $unit_name.'('.$rowadvance_rate.')';
                }
            }
        }
        $count = Db::name('kuyou_goods')->alias('g')
            ->join('kuyou_unit u','g.unit_id=u.id')
            ->where($where)->count();

        $result['list'] = $list;$result['count'] = $count;
        $this->success('查询成功',$result,200);
    }

    /**
     * 获取商品详情
     * @ApiMethod (POST)
     */
    public function getGoodsInfo(){
        $detail = input();
        $check = $this->checkParameter($detail,[
            'id|商品'=>'require|number',
        ]);
        if(isset($check['status'])){
            $this->error($check['msg'],'',$check['status']);
        }else{
            $goods_attr = isset($detail['goods_attr'])?$detail['goods_attr']:'';
            $row = Db::name('kuyou_goods')->where(['id'=>$detail['id'],'status'=>'1'])
                ->field('id,goods_code,goods_name,goods_barcode,goods_specification_id as goods_spec,goods_type_id,unit_id,
            goods_image,goods_images,note,more_unit,content')
                ->find();
            if(empty($row)){
                $this->error('未查询到商品数据','',500);
            }else{
                if(empty($row['goods_image'])){
                    $row['goods_image'] = $this->goods_image;
                }
                $row['goods_image'] = $this->web_site.$row['goods_image'];
                if(!empty($row['goods_images'])){
                    $goods_images = explode(',',$row['goods_images']);
                    foreach ($goods_images as $k=>$v){
                        $goods_images[$k] = $this->web_site.$v;
                    }
                    $row['goods_images'] = $goods_images;
                }

                $row['unit_data'] = $this->getGoodsUnit($row['id'],$goods_attr);
                $row['attr_data'] = $this->getGoodsAuxiliary($row['id']);

                $this->success('查询成功',$row,200);
            }
        }
    }

    /**
     * 获取商品多单位以及单位价格
     * @param int $id 商品ID
     * @return array
     */
    public function getGoodsUnit($id,$goods_attr=''){
        $row = Db::name('kuyou_goods')->where(['id'=>$id])
            ->field('more_unit,unit_id,more_unit_id,purchase,market_sell_price,wholesale_price,vip_price,discount,discount2,auxiliary')->find();
        if(empty($row)){
            return [];
        }

        $where = [];
        $where['goods_id'] = $id;
        if($goods_attr){
            $attr_id = Db::name('kuyou_goods_attr')->where($where)->where(['id'=>$goods_attr])
                ->value('attribute_id');
            if($attr_id){
                $where['attribute_id'] = $attr_id;
            }
        }
        $stock = Db::name('kuyou_goods_stock')->where($where)->sum('stock');

        if($row['more_unit']!=1){
            $unit_name = Db::name('kuyou_unit')->where(['id'=>$row['unit_id']])->value('name');

            if($row['auxiliary']==1){
                $where = [];
                if($goods_attr){
                    $where['attribute_id'] = $goods_attr;
                }
                $goods_attr = Db::name('kuyou_goods_attr')->where($where)->where(['goods_id'=>$id])
                    ->field('purchase,market_sell_price,wholesale_price,vip_price,discount,discount2')->find();
                $row['purchase'] = isset($goods_attr['purchase'])?$goods_attr['purchase']:0;
                $row['market_sell_price'] = isset($goods_attr['market_sell_price'])?$goods_attr['market_sell_price']:0;
                $row['wholesale_price'] = isset($goods_attr['wholesale_price'])?$goods_attr['wholesale_price']:0;
                $row['vip_price'] = isset($goods_attr['vip_price'])?$goods_attr['vip_price']:0;
                $row['discount'] = isset($goods_attr['discount'])?$goods_attr['discount']:0;
                $row['discount2'] = isset($goods_attr['discount2'])?$goods_attr['discount2']:0;
            }

            $goods_price = [];
            $goods_price[] = [
                'unit' => $row['unit_id'],
                'purchase' => $row['purchase'],
                'market_sell_price' => $row['market_sell_price'],
                'wholesale_price' => $row['wholesale_price'],
                'vip_price' => $row['vip_price'],
                'discount' => $row['discount'],
                'discount2' => $row['discount2'],
                'is_default' => 1,
                'name' => $unit_name,
                'stock' => $stock
            ];
        }else{
            $main_unit = $row['more_unit_id'];
            $unit_list = Db::name('kuyou_unit_conversion')
                ->where(['main_unit'=>$main_unit])
                ->order('advance_rate','ASC')
                ->field('vice_unit,advance_rate')
                ->select();
            $unit_id = [$main_unit];
            foreach ($unit_list as $unit_list_k=>$unit_list_v){
                $unit_id[] = $unit_list_v['vice_unit'];
            }

            $unit_list_id = Db::name('kuyou_unit_conversion')
                ->where(['main_unit'=>$main_unit])
                ->column('advance_rate','vice_unit');

            $goods_price = Db::name('kuyou_goods_price')->alias('g')
                ->join('kuyou_unit u','u.id=g.unit')
                ->where(['g.goods_id'=>$id])
                ->field('g.unit,g.purchase,g.market_sell_price,g.wholesale_price,g.vip_price,g.discount,g.discount2,g.is_default,u.name')
                ->order('g.is_default DESC')->select();
        }

        foreach ($goods_price as $list_k=>$list_v){
            if($list_v['is_default']==1){
                $goods_price[$list_k]['stock'] = is_null($stock)?0:$stock;
            }else{
                if(isset($unit_list_id[$list_v['unit']]) && $unit_list_id[$list_v['unit']]!=0){
                    $goods_price[$list_k]['stock'] = round($stock/$unit_list_id[$list_v['unit']],2);
                }else{
                    $goods_price[$list_k]['stock'] = is_null($stock)?0:$stock;
                }
            }
        }
        return $goods_price;
    }

    /**
     * 获取商品属性信息
     * @param int $id 商品ID
     * @return array
     */
    public function getGoodsAuxiliary($id){
        $auxiliary = Db::name('kuyou_auxiliary')->where(['status'=>1])->column('name','id');
        $goods_attr = Db::name('kuyou_goods_attr')->where(['goods_id'=>$id])
            ->field('id,attribute_id,attr_code,barcode,unit,purchase,market_sell_price,wholesale_price,vip_price,discount,discount2')->select();
        foreach ($goods_attr as $goods_attr_k=>$goods_attr_v){
            $aux_combination = Db::name('kuyou_aux_combination')->where(['id'=>$goods_attr_v['attribute_id']])->value('attr_ids');
            $goods_attr[$goods_attr_k]['attr_name'] = '';
            if($aux_combination){
                $aux_combination = explode('&',$aux_combination);
                foreach ($aux_combination as $aux_combination_k=>$aux_combination_v){
                    $aux_combination[$aux_combination_k] = $auxiliary[$aux_combination_v];
                }
                $aux_combination = implode('/',$aux_combination);
                $goods_attr[$goods_attr_k]['attr_name'] = $aux_combination;
            }

            unset($goods_attr[$goods_attr_k]['attribute_id']);
        }
        return $goods_attr;
    }

}
